package es.index.util;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public final class LockFile {
	private RandomAccessFile _raf = null;
	private FileChannel _fc = null;
	private FileLock _fl = null;

	private String _fileName = "";

	private String _fileAbsolutePath = "";

	public LockFile(File file) {
		if (file == null)
			return;
		_fileAbsolutePath = file.getAbsolutePath();
		try {
			_fileName = file.getName();
			_raf = new RandomAccessFile(file, "rw");
			_fc = _raf.getChannel();
			_fl = _fc.tryLock();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getAbsolutePath() {
		return _fileAbsolutePath;
	}

	public String getFileName() {
		return _fileName;
	}

	public void release() {
		try {
			_fl.release();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除文件
	 */
	public void delete() {
		release();
		close();
		File file = new File(_fileAbsolutePath);
		file.delete();
	}

	public void close() {
		try {
			_fl.close();
		} catch (IOException e2) {
			e2.printStackTrace();
		}
		_fl = null;
		try {
			_fc.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		_fc = null;
		try {
			_raf.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		_raf = null;
	}

	public void write(String value) {
		try {
			_raf.seek(0);
			_raf.setLength(value.length());
			_raf.write(value.getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void writeBytes(byte[] bytes, int offset) {
		try {
			_raf.seek(offset);
			_raf.setLength(offset + bytes.length);
			_raf.write(bytes);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String readLine() {
		try {
			_raf.seek(0);
			byte[] bytes = new byte[(int) _raf.length()];
			_raf.read(bytes);
			return new String(bytes);//.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}
}
